package service

import (
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"melon/server/global"
	"melon/server/model"
	"melon/server/utils/filesize"
	"mime/multipart"
	"time"
)

func CreateQiniuCurdFactory(prefix string) *QiniuModel {
	return &QiniuModel{global.MelonYml.GetString(prefix + ".Domain"),
		global.MelonYml.GetString(prefix + ".AccessKey"),
		global.MelonYml.GetString(prefix + ".SecretKey"),
		global.MelonYml.GetString(prefix + ".Bucket"),
	}
}

type QiniuModel struct {
	Domain    string
	AccessKey string
	SecretKey string
	Bucket    string
}

func (q *QiniuModel) GetFileList(prefix string) (ret []model.ListItem) {
	bucket := q.Bucket
	limit := 1000
	delimiter := ""
	//初始列举marker为空
	marker := ""

	mac := qbox.NewMac(q.AccessKey, q.SecretKey)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuabei,
		UseCdnDomains: false,
		UseHTTPS:      true,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	for {
		entries, _, nextMarker, hasNext, err := bucketManager.ListFiles(bucket, prefix, delimiter, marker, limit)
		if err != nil {
			fmt.Println("list error,", err)
			break
		}
		//print entries
		for _, entry := range entries {
			ret = append(ret, model.ListItem{
				Key:      entry.Key,
				Hash:     entry.Hash,
				Fsize:    filesize.FormatFileSize(entry.Fsize),
				PutTime:  time.Unix(entry.PutTime/1e7, 0).Format("2006-01-02 15:04:05"),
				MimeType: entry.MimeType,
				Type:     entry.Type,
				EndUser:  entry.EndUser,
			})
		}
		if hasNext {
			marker = nextMarker
		} else {
			break
		}
	}
	return
}

func (q *QiniuModel) UploadFile(key string, file multipart.File, fileSize int64) (retStr string, err error) {
	putPolicy := storage.PutPolicy{
		Scope: q.Bucket,
	}
	mac := qbox.NewMac(q.AccessKey, q.SecretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuabei,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	putExtra := storage.PutExtra{}
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	err = formUploader.Put(context.Background(), &ret, upToken, key, file, fileSize, &putExtra)
	retStr = q.Domain + "/" + ret.Key
	return
}

func (q *QiniuModel) DeleteFile(key string) (err error) {
	mac := qbox.NewMac(q.AccessKey, q.SecretKey)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuabei,
		UseCdnDomains: false,
		UseHTTPS:      true,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	err = bucketManager.Delete(q.Bucket, key)
	if err != nil {
		return
	}
	return nil
}

func (q *QiniuModel) DownloadFile(key string) string {
	mac := qbox.NewMac(q.AccessKey, q.SecretKey)
	deadline := time.Now().Add(time.Second * 3600).Unix() //1小时有效期
	privateAccessURL := storage.MakePrivateURL(mac, q.Domain, key, deadline)
	return privateAccessURL
}
